<?php
/**
 * Created by PhpStorm.
 * User: hebidu
 * Date: 15/7/2
 * Time: 14:22
 */

namespace Shop\Api;


use Common\Api\Api;
use Shop\Model\ProductPackageItemModel;
use Shop\Model\ProductPackageModel;

class ProductPackageApi extends Api{

    /**
     * 查询，不分页
     */
    const QUERY_NO_PAGING = "Shop/ProductPackage/queryNoPaging";
    /**
     * 查询，分页
     */
    const QUERY = "Shop/ProductPackage/query";
    /**
     * 查询，分页带数量
     */
    const QUERY_WITH_COUNT = 'Shop/ProductPackage/queryWithCount';

    /**
     * 添加
     */
    const ADD = "Shop/ProductPackage/add";
    /**
     * 保存
     */
    const SAVE = "Shop/ProductPackage/save";
    /**
     * 获取信息
     */
    const GET_INFO = "Shop/ProductPackage/getInfo";
    /**
     * 保存根据ID主键
     */
    const SAVE_BY_ID = "Shop/ProductPackage/saveByID";

    /**
     * 删除
     */
    const DELETE = "Shop/ProductPackage/delete";

    /**
     * 套餐详情
     */
    const PACKAGE_DETAIL = "Shop/ProductPackage/packageDetail";

    /**
     * 套餐保存
     */
    const PACKAGE_SAVE = "Shop/ProductPackage/packageSave";

    /**
     * 套餐删除
     */
    const PACKAGE_DELETE = "Shop/ProductPackage/packageDelete";


    protected function _init(){
        $this->model = new ProductPackageModel();
    }

    public function packageDetail($package_id){

        $model = $this->model;

        $result = $model->field('id as package_id, package_name, package_price, package_img, create_time, end_time, package_desc, dt_type')->where(['id' => $package_id])->find();
        if ($result === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }
        if(is_null($result)){
            return $this->apiReturnSuc($result);
        }

        $package_info['main_info'] = $result;

        $result = $model->alias('PP')->where(['PP.id' => $package_id,'PIA.type'=>6015])
            ->field('PP.id as package_id, PP.package_name, PP.create_time, PP.end_time, PP.package_price, PP.package_img, PP.package_desc,
            PP.dt_type, PI.p_id, PI.is_main, P.name as product_name, PI.sku_id, PS.sku_desc,PIA.img_id,PS.icon_url')
            ->join('__PRODUCT_PACKAGE_ITEM__ AS PI  ON PI.package_id = PP.id','LEFT')
            ->join('__PRODUCT__ AS P ON P.id = PI.p_id','LEFT')
            ->join('__PRODUCT_SKU__ AS PS ON PS.id = PI.sku_id','LEFT')
            ->join('__PRODUCT_IMAGE__ AS PIA ON PIA.pid = PI.p_id','LEFT')
            ->select();

        if ($result === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        } else {
            $package_info['items'] = $result;
            return $this -> apiReturnSuc($package_info);
        }

    }

    public function packageDelete($package_ids=[]){

        $model = $this->model;
        $item_model = new ProductPackageItemModel();
        $model->startTrans();

        //删除套餐
        $map = ['id'=>['in',$package_ids]];
        $result = $model->where($map)->delete();
        if($result === false){
            $error = $this -> model -> getDbError();
            $model->rollback();
            return $this -> apiReturnErr($error);
        }

        //删除套餐中所有商品
        $map = ['package_id'=>['in',$package_ids]];
        $result = $item_model->where($map)->delete();
        if($result === false){
            $error = $this -> model -> getDbError();
            $model->rollback();
            return $this -> apiReturnErr($error);
        }
        $model->commit();
        return $this -> apiReturnSuc('删除成功');

    }

    public function packageSave($package_info){

        $package_id = $package_info['package_id'];
        $items = $package_info['items'];

        $model = $this->model;
        $item_model = new ProductPackageItemModel();

        $model->startTrans();

        if($package_id>0){
            //修改package
            $data = [
                'package_name' => $package_info['package_name'],
                'end_time' => $package_info['end_time'],
                'package_price' => $package_info['package_price'],
                'package_img' => $package_info['package_img'],
                'package_desc' => $package_info['package_desc'],
                'dt_type' => $package_info['dt_type']
            ];
            $map = [
                'id' => $package_id
            ];
            $result = $model->where($map)->save($data);
            if($result === false){
                $error = $this -> model -> getDbError();
                $model->rollback();
                return $this -> apiReturnErr($error);
            }

            //修改item,先删除旧的
            $map = ['package_id' => $package_id];
            $result = $item_model->where($map)->delete();
            if($result === false){
                $error = $this -> model -> getDbError();
                $model->rollback();
                return $this -> apiReturnErr($error);
            }
            //创建item
            $dataList = [];
            foreach($items as $val){
                $dataList[] = [
                    'package_id' => $package_id,
                    'p_id' => $val['pid'],
                    'sku_id' => $val['sku_id'],
                    'is_main' => $val['is_main']
                ];
            }
            $result = $item_model->addAll($dataList);
            if($result === false){
                $error = $this -> model -> getDbError();
                $model->rollback();
                return $this -> apiReturnErr($error);
            }


        }else{
            //创建package
            $data = [
                'package_name' => $package_info['package_name'],
                'end_time' => $package_info['end_time'],
                'package_price' => $package_info['package_price'],
                'package_img' => $package_info['package_img'],
                'package_desc' => $package_info['package_desc'],
                'dt_type' => $package_info['dt_type'],
                'create_time' => time()
            ];

            $result = $model->add($data);

            if($result === false){
                $error = $this -> model -> getDbError();
                $model->rollback();
                return $this -> apiReturnErr($error);
            }
            $package_id = $result;

            //创建item
            $dataList = [];
            foreach($items as $val){
                $dataList[] = [
                    'package_id' => $package_id,
                    'p_id' => $val['pid'],
                    'sku_id' => $val['sku_id'],
                    'is_main' => $val['is_main']
                ];
            }
            $result = $item_model->addAll($dataList);
            if($result === false){
                $error = $this -> model -> getDbError();
                $model->rollback();
                return $this -> apiReturnErr($error);
            }

        }
        $model->commit();
        return $this -> apiReturnSuc($package_id);


    }


}